package hc.bre.rest.admin

import org.apache.shiro.realm.Realm
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition
import org.apache.shiro.web.mgt.CookieRememberMeManager
import org.apache.shiro.web.mgt.DefaultWebSecurityManager
import org.apache.shiro.web.servlet.SimpleCookie
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration

@Configuration
@groovy.transform.CompileStatic
class AuthConfiguration {
	@Bean
	public Realm realm() {
		return new AuthRealm();
	}
	
	//rememberMe https://www.cnblogs.com/starktan/p/9608692.html
	@Bean
	public SimpleCookie rememberMeCookie() {
		//这个参数是cookie的名称，对应前端的checkbox的name = rememberMe
		SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
		//如果httyOnly设置为true，则客户端不会暴露给客户端脚本代码，使用HttpOnly cookie有助于减少某些类型的跨站点脚本攻击；
		simpleCookie.setHttpOnly(true);
		//记住我cookie生效时间,单位是秒
		//TODO MOVE THE DURATION TO APPLICATION.PROPERTIES
		simpleCookie.setMaxAge(180*24*60);
		return simpleCookie;
	}
	
	@Bean
	public CookieRememberMeManager rememberMeManager() {
		CookieRememberMeManager cookieRememberMeManager = new CookieRememberMeManager();
		//rememberme cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度（128 256 512 位），通过以下代码可以获取
		//KeyGenerator keygen = KeyGenerator.getInstance("AES");
		//SecretKey deskey = keygen.generateKey();
		//System.out.println(Base64.encodeToString(deskey.getEncoded()));
		Base64 b;
		byte[] cipherKey = org.apache.shiro.codec.Base64.decode("4K9Zpsz0r8S34FpSL589mw==");
		cookieRememberMeManager.setCipherKey(cipherKey);
		cookieRememberMeManager.setCookie(rememberMeCookie());
		return cookieRememberMeManager;
	}
	
//	@Bean
//	public org.apache.shiro.mgt.SecurityManager securityManager() {
//		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//		securityManager.setRealm(new CustomRealm());
//		securityManager.setRememberMeManager(rememberMeManager());
//		return securityManager;
//	}
	
	@Bean
	public ShiroFilterChainDefinition shiroFilterChainDefinition() {
		DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
		
		//https://blog.csdn.net/qq_33591200/article/details/82884304
		
//		// logged in users with the 'admin' role
//		chainDefinition.addPathDefinition("/admin/**", "authc, roles[admin]");
//		// logged in users with the 'document:read' permission
//		chainDefinition.addPathDefinition("/docs/**", "authc, perms[document:read]");
//		// all other paths require a logged in user
//		chainDefinition.addPathDefinition("/**", "authc");
		
//		chainDefinition.addPathDefinition("/docs/*", "anon");
		
		//'user' interceptor used to 'remember me'. /hello/world/setup can be anything
		chainDefinition.addPathDefinition("/hello/world/setup", "user");
		
		//all other path controlled by annotation or 'permit' code
		chainDefinition.addPathDefinition("/**", "anon");
		
		return chainDefinition;
	}
}
